package com.haojin.haojintimingmonitor.utils;

import cn.hutool.extra.spring.SpringUtil;
import com.haojin.haojintimingmonitor.config.ChuangLanHomeProperties;
import com.haojin.haojintimingmonitor.config.MessageInfo;
import com.haojin.haojintimingmonitor.config.YunpianConfigInfo;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class SmsUtils {

    private static final RestTemplate restTemplate = SpringUtil.getBean(RestTemplate.class);
    private static final ChuangLanHomeProperties chuangLanHomeProperties = SpringUtil.getBean(ChuangLanHomeProperties.class);
    private static final MessageInfo messageInfo  = SpringUtil.getBean(MessageInfo.class);
    private static final YunpianConfigInfo yunpianConfigInfo = SpringUtil.getBean(YunpianConfigInfo.class);
    public static void sendMessage(Integer timing,String tableName,String appName){
        String msg = String.format(messageInfo.getMsg(), appName,tableName, timing, new SimpleDateFormat("MM-dd HH:mm").format(new Date()));
        log.info("发送信息，{}",msg);

        OkHttpClient client = new OkHttpClient();

        // Prepare data
        RequestBody formBody = new FormBody.Builder()
                .add("apikey", yunpianConfigInfo.getApikey())
                .add("mobile", yunpianConfigInfo.getMobile() )
                .add("text", msg)
                .build();

        // Create request
        Request request = new Request.Builder()
                .url(yunpianConfigInfo.getUrl())
                .post(formBody)
                .build();

        try (Response response = client.newCall(request).execute()) {
            // Print response
            System.out.println(response.body().string());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
